import { DownOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, message, Switch, Divider, Icon } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { ListItem } from './data';
import { queryRule, updateRule, addRule, removeRule } from './service';
import moment from 'moment';
import { Dispatch } from 'redux';
import { bdExec } from '@/helpers/RequestHelper';

interface RuleListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
}

/**
 * 添加节点
 */
const handleAdd = async (fields: FormValueType) => {
  return bdExec({ fn: addRule, args: fields, successMsg: '添加成功', failMsg: '添加失败请重试！' });
};

/**
 * 更新节点
 */
const handleUpdate = async (fields: FormValueType) => {
  return bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

/**
 *  删除节点
 */
const handleRemove = async (selectedRows: ListItem[]) => {
  if (!selectedRows) return true;
  const ids: any = selectedRows.map(row => row.id).toString();
  return bdExec({ fn: removeRule, args: { ids }, successMsg: '删除成功，即将刷新', failMsg: '删除失败，请重试！' });
};

const OpLogList: React.FC<RuleListProps> = (props) => {

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);
  const [stateData, setStateData] = useState<any>({ data: {} });
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<ListItem>[] = [
    {
      title: '用户名称',
      dataIndex: 'user_name',
      width: 120,
    },
    // {
    //   title: '角色名称',
    //   dataIndex: 'name',
    //   width: 120,
    // },
    {
      title: '原数据',
      dataIndex: 'original_data',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '路由',
      dataIndex: 'req_method',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '请求数据',
      dataIndex: 'request_data',
      hideInSearch: true,
      onCell: () => {
        return {
          style: {
            maxWidth: 600,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer'
          }
        }
      },
    },
    {
      title: '操作ip',
      dataIndex: 'op_ip',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '操作时间',
      dataIndex: 'created_at',
      sorter: true,
      hideInSearch: true,
      width: 200,
      render: (val: any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 80,
      render: (_: any, record: React.SetStateAction<{}>) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            详情
          </a>
        </>
      ),
    },
  ];

  const getListData = (params: any) => {
    return queryRule(params).then((res: any) => {
      if (res.code === 0) {
        setStateData(res)
        return res.data.listData;
      } else {
        message.error(res.msg);
      }
    })
  }


  return (
    <PageHeaderWrapper>

      <ProTable<ListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="key"
        pagination={{
          showSizeChanger: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          // <Button icon={'plus'} type="primary" onClick={() => handleModalVisible(true)}>
          //   新建
          // </Button>,
          // selectedRows && selectedRows.length > 0 && (
          //   <Dropdown
          //     overlay={
          //       <Menu
          //         onClick={async e => {
          //           if (e.key === 'remove') {
          //             await handleRemove(selectedRows);
          //             setRowKeys([]);
          //             action.reload();
          //           }
          //         }}
          //         selectedKeys={[]}
          //       >
          //         <Menu.Item key="remove">批量删除</Menu.Item>
          //       </Menu>
          //     }
          //   >
          //     <Button>
          //       批量操作 <DownOutlined />
          //     </Button>
          //   </Dropdown>
          // ),
        ]}
        tableAlertRender={(selectedRowKeys, selectedRows) => (
          <div>
            已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
            {/* <span>
              服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万
            </span> */}
          </div>
        )}
        request={(params) => getListData(params)}
        columns={columns}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            setRowKeys(selectedRowKeys);
          },
          selectedRowKeys: rowKeys,
        }}
      />

      <CreateForm
        onSubmit={async (value) => {
          const success: any = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        otherValues={{
          common: stateData.data.common || {},
        }}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => handleUpdateModalVisible(false)}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
          otherValues={{
            common: stateData.data ?.common || {},
          }}
        />
      ) : null}
    </PageHeaderWrapper>
  );
};

export default Form.create<RuleListProps>()(OpLogList);
